package waitGroup

import (
	"fmt"
	"runtime"
	"sync"
	"time"
)

func testBlockFmt() {
	a := []int{0}
	for i := 1; i < 200000; i++ {
		a = append(a, i)
	}
	s := time.Now()
	fmt.Println(s)
	x := &sync.WaitGroup{}
	x.Add(1)
	go testOutCap(a, x)
	x.Wait()
	e := time.Now()
	fmt.Println(e.Sub(s))
}

func testOutCap(strList []int, s *sync.WaitGroup) {
	defer s.Done()
	sumLen := len(strList)
	cap := 2000
	count := (int)(sumLen / cap)
	fmt.Println("count :", count)
	s.Add(count - 1)
	for i := 0; i <= count; i++ {
		if (1+i)*cap > sumLen {
			go outBlock(strList[i*cap:sumLen], s)
			//outblock(strList[i*cap:sumLen])
		} else {
			go outBlock(strList[i*cap:(1+i)*cap], s)
			//outblock(strList[i*cap:(1+i)* cap ])
		}
	}
}

func outBlock(block []int, s *sync.WaitGroup) {
	defer s.Done()
	for _, k := range block {
		fmt.Println(k)
	}
}

func outblock(block []int) {
	for _, k := range block {
		fmt.Println(k)
	}
}

func waitT1() {
	wait := &sync.WaitGroup{}
	maps := make([]map[int]int, 0)
	for z := 0; z < 30; z++ {
		temp := make(map[int]int, 0)
		temp[z] = z
		maps = append(maps, temp)
	}
	for i := 0; i < 20; i++ {
		wait.Add(1)
		if len(maps) > 20 {
			fmt.Println("是我")
			go callMe1(i, wait, maps[0:19])
		} else {
			go callMe1(i, wait, maps)
		}

	}
	wait.Wait()
	fmt.Println("hao le")
}

func callMe1(i int, wait *sync.WaitGroup, mps []map[int]int) {
	defer func() {
		wait.Done()
	}()
	//fmt.Println(mps[i][i])
	time.Sleep(1 * time.Second)
}

func te() {
	p := &sync.Pool{
		New: func() interface{} {
			return 0
		},
	}
	runtime.GC()
	a := p.Get().(int)
	p.Put(1)
	b := p.Get().(int)
	fmt.Println(a, b)
}

type waitGroupTestStruct struct {
	wait *sync.WaitGroup
}

func startWaitTest1(cb func(waitGroupTestStruct)) {
	waitT := new(waitGroupTestStruct)
	waitT.wait = new(sync.WaitGroup)
	cb(*waitT)
}

func (w *waitGroupTestStruct) start() {
	w.wait.Add(1)
	go w.loop(10)
	fmt.Println(".....1")
}

func (w *waitGroupTestStruct) loop(i int) {
	defer w.wait.Done()
	for {
		fmt.Println(i)
		i--
		if i == 0 {
			go func() {
				fmt.Println("Hi")
				w.wait.Wait()
			}()
			return
		}
	}
}
